package com.vast.admin.service;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.vast.admin.entity.*;
import com.vast.admin.entity.dto.TemplateFieldsDto;
import com.vast.admin.entity.enums.OperatorEum;
import com.vast.admin.entity.enums.QueryOrderEnum;
import com.vast.admin.mapper.TempleteMapper;
import com.vast.admin.service.impl.CompanyService;
import com.vast.admin.utils.PlaceholderResolver;
import com.vast.admin.utils.QueryBuilder;
import com.vast.admin.utils.TableFieldColumnsUtils;
import com.vast.admin.utils.WordUtil;
import com.vast.common.core.domain.entity.SysUser;
import com.vast.common.utils.FileUtils;
import com.vast.common.constant.MessageCode;
import com.vast.common.core.domain.Result;
import com.vast.system.exception.BusinessException;
import com.vast.system.utils.Constant;
import com.vast.system.utils.OssUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jodconverter.DocumentConverter;
import org.jodconverter.office.OfficeException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TempleteService extends ServiceImpl<TempleteMapper, Templete> {

    @Autowired
    private TempleteRecordService templeteRecordService;

    @Autowired
    private PlaceholderService placeholderService;

    @Autowired
    private PlaceholderResolver placeholderResolver;

    @Autowired
    private DocumentConverter documentConverter;

    @Autowired
    private TempleteRecordSignatureService templeteRecordSignatureService;

    @Autowired
    private OssUtils ossUtils;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PlaceholderTemplateService placeholderTemplateService;

    /**
     * 模板保存
     *
     * @param templete
     * @param manager
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveTemplete(Templete templete, SysUser manager) {
        if (templete.getId() == null && StringUtils.isEmpty(templete.getTempletePath())) {
            throw new BusinessException(new Result(MessageCode.ERROR, "添加模板时必须上传模板文件"));
        }
        //获取合同模板中的占位符
        List<Placeholder> placeholders = placeholderResolver.getPlaceholder(WordUtil.readWord(FileUtils.getLocation() + templete.getTempletePath()));
        //企业签署客户
        List<String> companyParts = new ArrayList<>();
        //个人签署客户
        List<String> customerParts = new ArrayList<>();
        //已处理
        List<String> processesBelong = new ArrayList<>();
        for (Placeholder placeholder : placeholders) {
            if (StringUtils.isEmpty(placeholder.getPlaceholderBelong())) {
                placeholder.setPlaceholderBelong("其他");
            }
            PlaceholderTemplate placeholderNameTemplate =
                    placeholderTemplateService.getPlaceholderNameTemplateByBelongAndName(placeholder.getPlaceholderBelong(), placeholder.getPlaceholderName());
            if (placeholderNameTemplate != null) {
                placeholder.setRequire(placeholderNameTemplate.getRequire());
                placeholder.setPlaceholderTag(placeholderNameTemplate.getPlaceholderTag());
            }
            if (!processesBelong.contains(placeholder.getPlaceholderBelong())) {
                PlaceholderTemplate placeholderBelongTemplate =
                        placeholderTemplateService.getPlaceholderBelongTemplateByBelong(placeholder.getPlaceholderBelong());
                if (placeholderBelongTemplate != null) {
                    switch (placeholderBelongTemplate.getBelongPartType()) {
                        case 1:
                            companyParts.add(placeholder.getPlaceholderBelong());
                            break;
                        case 2:
                            customerParts.add(placeholder.getPlaceholderBelong());
                            break;
                    }
                }
                processesBelong.add(placeholder.getPlaceholderBelong());
            }
        }
        if (StringUtils.isNotEmpty(templete.getTempletePath())) {
            //保存模板
            try {
                templete.setTempletePath(FileUtils.moveFile(templete.getTempletePath(), FileUtils.FileType.TEMPLETE));
            } catch (IOException e) {
                throw new BusinessException(Result.ERROR, "文件处理失败");
            }
            templete.setTempletePdfPath(word2Pdf(templete.getTempletePath()));
            String objectName = FileUtils.FileType.TEMPLETE.getValue() + "/" + templete.getTempletePdfPath().substring(templete.getTempletePdfPath().lastIndexOf("/") + 1);
            ossUtils.uploadFile(objectName, FileUtils.getLocation() + templete.getTempletePdfPath());
            templete.setPreviewUrl(ossUtils.getPulicFileUrl(objectName));
        }

        if (templete.getId() != null) {
            templete.setUpdateBy(manager.getUserId());
            templete.setUpdateTime(new Date());
        } else {
            templete.setCreateBy(manager.getUserId());
            templete.setCreateTime(new Date());
        }
        TempleteRecord templeteRecord = new TempleteRecord();
        BeanUtils.copyProperties(templete, templeteRecord);
        super.saveOrUpdate(templete);
        //保存模板记录
        templeteRecord.setTempleteId(templete.getId());
        templeteRecord.setIsUse(1);
        templeteRecord.setCustomerPart(StringUtils.join(customerParts, ","));
        templeteRecord.setCompanyPart(StringUtils.join(companyParts, ","));
        templeteRecordService.save(templeteRecord);
        templete.setRecordId(templeteRecord.getId());
        //修改模板的当前使用的模板记录
        UpdateWrapper<Templete> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", templete.getId());
        updateWrapper.set(Templete.COL_RECORD_ID, templeteRecord.getId());
        super.update(updateWrapper);

        //解析模板中的占位符
        analyseTemplete(templete, manager, placeholders);
    }

    /**
     * 解析模板占位符
     *
     * @param templete
     * @param manager
     */
    private void analyseTemplete(Templete templete, SysUser manager, List<Placeholder> placeholders) {
        for (Placeholder placeholder : placeholders) {
            placeholder.setTempleteId(templete.getId());
            placeholder.setTempleteRecordId(templete.getRecordId());
            placeholder.setCreateBy(manager.getUserId());
            placeholder.setCreateTime(new Date());
        }
        placeholderService.saveBatch(placeholders);
    }

    /**
     * word转pdf
     *
     * @param wordPath
     * @return
     */
    private String word2Pdf(String wordPath) {
        String pdfPath = FileUtils.FileType.TEMPLETE.getValue() + "/" + System.currentTimeMillis() + ".pdf";
        try {
            documentConverter.convert(new File(FileUtils.getLocation() + wordPath)).to(new File(FileUtils.getLocation() + pdfPath)).execute();
            return pdfPath;
        } catch (OfficeException e) {
            throw new BusinessException("word转pdf失败");
        }
    }

    public IPage<Templete> queryList(SysUser manager, Page<Templete> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
        QueryWrapper<Templete> queryWrapper = new QueryWrapper<>();
        Map<String, String> fieldColumns = TableFieldColumnsUtils.getInstance().getFieldTableColumns(Templete.class);
        if (listMode) {
            // size 小于 0 不在查询 total 及分页，自动调整为列表模式。
            // 注意！！这个地方自己控制好！！
            page.setSize(-1);
        }
        if (!StringUtils.isEmpty(queryItems)) {
            List<QueryBuilder> queryBuilders = new ArrayList<>();
            String[] queryItemArr = queryItems.split(";");
            if (queryItemArr.length > 0) {
                for (String queryItemStr : queryItemArr) {
                    String[] itemArr = queryItemStr.split(",");
                    if (itemArr.length == 3) {
                        String as = itemArr[1];
                        String params = itemArr[2];
                        if (!StringUtils.isEmpty(params)) {
                            queryBuilders.add(new QueryBuilder(itemArr[0], OperatorEum.valueOf(as), itemArr[2]));
                        }
                    }
                }
            }

            for (QueryBuilder queryBuilder : queryBuilders) {
                //查询字段
                String field = queryBuilder.getField();
                //查询参数值
                String params = queryBuilder.getParams();
                if (fieldColumns.containsKey(field) && !StringUtils.isEmpty(params)) {
                    //表属性
                    String tableColumn = fieldColumns.get(field);
                    if (queryBuilder.getAs() == OperatorEum.EQ) {
                        queryWrapper.eq(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKE) {
                        queryWrapper.like(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKELEFT) {
                        queryWrapper.likeLeft(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LIKERIGHT) {
                        queryWrapper.likeRight(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.GE) {
                        queryWrapper.ge(tableColumn, params);
                    } else if (queryBuilder.getAs() == OperatorEum.LE) {
                        queryWrapper.le(tableColumn, params);
                    }
                }
            }
        }

        if (!StringUtils.isEmpty(orderField)) {
            String[] orderByColumns = orderField.split(",");
            String queryOrderByColumns = "";
            if (orderByColumns.length > 0) {
                StringBuilder sb = new StringBuilder();
                for (String orderByColumn : orderByColumns) {
                    if (fieldColumns.containsKey(orderByColumn)) {
                        sb.append(fieldColumns.get(orderByColumn)).append(",");
                    }
                }
                if (sb.length() > 0) {
                    queryOrderByColumns = sb.deleteCharAt(sb.length() - 1).toString();
                }
            }
            if (!StringUtils.isEmpty(queryOrderByColumns)) {
                if (order == null) {
                    order = QueryOrderEnum.ASC;
                }
                if (order == QueryOrderEnum.ASC) {
                    queryWrapper.orderByAsc(queryOrderByColumns);
                } else if (order == QueryOrderEnum.DESC) {
                    queryWrapper.orderByDesc(queryOrderByColumns);
                }
            }

        }


        if (!manager.isHasRole(Constant.SUPER_ADMIN)) {//超级管理员
            queryWrapper.and(w -> w.eq(Templete.COL_COMPANY_ID, manager.getCompanyId()).or().eq(Templete.COL_COMPANY_ID, 0));
        }

        queryWrapper.orderByDesc(Templete.COL_COMPANY_ID).orderByAsc(Templete.COL_TEMPLETE_NAME);
        IPage<Templete> result = baseMapper.selectPage(page, queryWrapper);
        for (Templete record : result.getRecords()) {
            Long companyId = record.getCompanyId();
            if (companyId == 0) {
                record.setCompanyName("公共模板库");
            } else if(companyId != null && companyId > 0){
                Company company = companyService.getById(companyId);
                if(company != null){
                    record.setCompanyName(company.getName());
                }
            }
        }

        return result;
    }

    /**
     * 获取模板列表
     * @param manager
     * @return
     */
    public List<Templete> getList(SysUser manager) {
        QueryWrapper<Templete> queryWrapper = new QueryWrapper<>();
        if (!manager.isHasRole(Constant.SUPER_ADMIN)) {//超级管理员
            queryWrapper.and(w -> w.eq(Templete.COL_COMPANY_ID, manager.getCompanyId()).or().eq(Templete.COL_COMPANY_ID, 0));
        }
        List<Templete> templetes = super.list(queryWrapper);
        templetes.stream().forEach(template -> {
            Long companyId = template.getCompanyId();
            if (companyId == 0) {
                template.setCompanyName("公共模板库");
            } else if(companyId != null && companyId > 0){
                template.setCompanyName("私有模板库");
            }
        });
        return templetes;
    }

    public boolean addOrUpdate(SysUser manager, Templete bean) {
        if (bean.getId() == null) {
            bean.setCreateBy(manager.getUserId());
            bean.setUpdateBy(manager.getUserId());
            bean.setCreateTime(DateTime.now());
            bean.setUpdateTime(DateTime.now());
            bean.setValid(1);
            //添加
//            baseMapper.insert(bean);

            saveTemplete(bean, manager);

            return true;
        } else {
            bean.setUpdateBy(manager.getUserId());
            bean.setUpdateTime(DateTime.now());
            bean.setValid(1);
            baseMapper.updateById(bean);
            TempleteRecord templeteRecord = new TempleteRecord();
            BeanUtils.copyProperties(bean, templeteRecord);
            templeteRecord.setId(bean.getRecordId());
            templeteRecordService.updateById(templeteRecord);
//            baseMapper.updateById(bean);



//            saveTemplete(bean, manager);
//
            return true;
//            return roleMenuService.saveBatch(roleMenus);
        }
    }

    public Templete info(SysUser manager, Long id) {
        Templete bean = baseMapper.selectById(id);
        TempleteRecord templeteRecord = templeteRecordService.getByTempleteId(bean.getId());
        if (templeteRecord != null) {//获取合同金额
            bean.setCostType(templeteRecord.getCostType());
            bean.setPayAmount(templeteRecord.getPayAmount());
            bean.setPayRatio(templeteRecord.getPayRatio());
            bean.setMinAmount(templeteRecord.getMinAmount());
        }
        return bean;
    }


    public boolean delete(SysUser manager, Long[] ids) {

        List<Long> idsList = java.util.Arrays.asList(ids);
        int count = baseMapper.deleteBatchIds(idsList);

        return count == ids.length;

    }

    /**
     * 保存合同模板设置
     *
     * @param templateFieldsDtos
     * @param manager
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveTempleteSettings(List<TemplateFieldsDto> templateFieldsDtos, SysUser manager) {
        if (templateFieldsDtos == null || templateFieldsDtos.isEmpty()) {
            throw new BusinessException(new Result(MessageCode.ERROR, "参数错误"));
        }
        boolean flag = false;
        TempleteRecord templeteRecord = new TempleteRecord();
        templeteRecord.setCompanyPart(" ");
        templeteRecord.setCustomerPart(" ");
        List<Placeholder> placeholderList = new ArrayList<>();
        //按sort排序
        templateFieldsDtos = templateFieldsDtos.stream().filter(o -> {
            if (o.getSort() == null) {
                throw new BusinessException(new Result(MessageCode.ERROR, o.getLabel() + "未添加排序值"));
            }
            return true;
        }).sorted(Comparator.comparingInt(TemplateFieldsDto::getSort)).collect(Collectors.toList());
        String placeholderSort = null;
        TempleteRecord tmp = null;
        //所有的签章位置
        List<TempleteRecordSignature> allTempleteRecordSignature = new ArrayList<>();
        for (TemplateFieldsDto templateFieldsDto : templateFieldsDtos) {
            if (templeteRecord.getId() == null) {
                //模板记录id
                templeteRecord.setId(templateFieldsDto.getTemplateRecordId());
                tmp = templeteRecordService.getById(templateFieldsDto.getTemplateRecordId());
                if (tmp == null) {
                    throw new BusinessException(new Result(MessageCode.ERROR, "未找到合同模板"));
                }
            }
            //1: '企业方', 2: '客户方', 3: '担保方', 4: '其他企业'
            Integer type = templateFieldsDto.getType();
            if (type == 1 || type == 3 || type == 4) {
                if (StringUtils.isNotEmpty(templeteRecord.getCompanyPart())) {
                    templeteRecord.setCompanyPart(templeteRecord.getCompanyPart() + "," + templateFieldsDto.getLabel());
                } else {
                    templeteRecord.setCompanyPart(templateFieldsDto.getLabel());
                }
            } else if (type == 2) {
                if (StringUtils.isNotEmpty(templeteRecord.getCustomerPart())) {
                    templeteRecord.setCustomerPart(templeteRecord.getCustomerPart() + "," + templateFieldsDto.getLabel());
                } else {
                    templeteRecord.setCustomerPart(templateFieldsDto.getLabel());
                }
            } else if (type == 0) {

            } else {
                if (StringUtils.isNotEmpty(templeteRecord.getThirdPart())) {
                    templeteRecord.setThirdPart(templeteRecord.getThirdPart() + "," + templateFieldsDto.getLabel());
                } else {
                    templeteRecord.setThirdPart(templateFieldsDto.getLabel());
                }
            }

            List<Placeholder> placeholders = templateFieldsDto.getItems();

            if (placeholders != null && !placeholders.isEmpty()) {
                boolean isContainsSignature = false;
                for (Placeholder placeholder : placeholders) {
                    placeholder.setUpdateBy(manager.getUserId());
                    placeholder.setUpdateTime(DateTime.now());
                    placeholder.setValid(1);

                    if (placeholder.getPlaceholderTag() == 1) {

                    } else if (placeholder.getPlaceholderTag() == 5) {
                        placeholder.setRequire(-1);
                        isContainsSignature = true;
                        //解析签章位置
                        List<TempleteRecordSignature> signatureDtos = getSignaturePosition(FileUtils.getLocation() + tmp.getTempletePdfPath(), templateFieldsDto.getLabel() + "." + placeholder.getPlaceholderName());
                        if(!signatureDtos.isEmpty()){
                            for (TempleteRecordSignature signatureDto : signatureDtos) {
                                signatureDto.setTempleteRecordId(tmp.getId());
                                if (type == 1 || type == 3 || type == 4) {
                                    //企业
                                    signatureDto.setType(1);
                                } else if (type == 2) {
                                    //客户
                                    signatureDto.setType(2);
                                }
                                signatureDto.setPartName(templateFieldsDto.getLabel());
                            }
                            allTempleteRecordSignature.addAll(signatureDtos);
                        }
                    }
                }
                if (templateFieldsDto.getType() != 0 && !isContainsSignature) {
                    throw new BusinessException(new Result(MessageCode.ERROR, templateFieldsDto.getLabel() + "未设置签章属性"));
                }
            }
            placeholderList.addAll(placeholders);
            if (placeholderSort == null) {
                placeholderSort = templateFieldsDto.getLabel();
            } else {
                placeholderSort += "," + templateFieldsDto.getLabel();
            }
        }
        templeteRecord.setPlaceholderSort(placeholderSort);

        //检查是否包含还款计划 6借款期数 7月利率 8还款方式 9每月还款日 10合同金额
        checkRepaymentPlan(templateFieldsDtos, templeteRecord.getId());

        //保存模板记录
        templeteRecord.setUpdateBy(manager.getUserId());
        templeteRecord.setUpdateTime(new Date());
        templeteRecordService.updateById(templeteRecord);
        updateTempleteStatus(tmp.getTempleteId(), 2, manager);
        //保存签章位置
        if(!allTempleteRecordSignature.isEmpty()){
            templeteRecordSignatureService.remove(new QueryWrapper<TempleteRecordSignature>().eq(TempleteRecordSignature.COL_TEMPLETE_RECORD_ID, templeteRecord.getId()));
            templeteRecordSignatureService.saveBatch(allTempleteRecordSignature);
        }

        //批量保存
        flag = placeholderService.saveOrUpdateBatch(placeholderList);


        return flag;
    }

    /**
     * 检查合同模板是否包含还款计划的相关设置
     * @param templeteRecordId
     */
    private void checkRepaymentPlan(List<TemplateFieldsDto> templateFieldsDtos, Long templeteRecordId) {
        int[] tag = new int[] {6 ,7 ,8, 9, 10};
        String[] name = new String[] {"借款期数", "月利率", "还款方式", "每月还款日", "合同金额"};
        Placeholder repaymentPlan = placeholderService.getPlaceholderByName(templeteRecordId, PlaceholderResolver.REPAYMENT_PLAN_FIELD);
        if (repaymentPlan == null) {
            //合同模板不包含还款计划
            return;
        }
        String errorMsg = null;
        for (int i = 0; i < tag.length; i ++) {
            if (!isContainsTag(templateFieldsDtos, tag[i])) {
                if (errorMsg == null) {
                    errorMsg = name[i];
                } else {
                    errorMsg += "," + name[i];
                }
            }
        }
        if (errorMsg != null) {
            throw new BusinessException(new Result(MessageCode.ERROR, "合同模板中包含 " + PlaceholderResolver.REPAYMENT_PLAN_FIELD + " ，但无类型为 " + errorMsg + " 的属性"));
        }
    }

    private boolean isContainsTag(List<TemplateFieldsDto> templateFieldsDtos, int tag) {
        for (TemplateFieldsDto templateFieldsDto : templateFieldsDtos) {
            for (Placeholder placeholder : templateFieldsDto.getItems()) {
                if (placeholder.getPlaceholderTag().intValue() == tag) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 根据pdf中的关键字，获取文字的绝对位置，从而确定签章位置
     *
     * @param filePath pdf文件的绝对地址
     * @return x与y值
     * @throws IOException
     */
    private static List<TempleteRecordSignature> getSignaturePosition(String filePath, String keyword) {
        List<TempleteRecordSignature> signatureDtos = new ArrayList<>();
        try {
            PdfReader pdfReader = new PdfReader(filePath);

            PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);
            int pageTotalNum = pdfReader.getNumberOfPages();
//            signature.setTotalPageNum(pageTotalNum);

            Rectangle pageSize = pdfReader.getPageSize(1);
            //页面高宽
            float height = pageSize.getHeight();
            float width = pageSize.getWidth();
            //页面高宽
//        System.out.println("width = "+width+", height = "+height);
//        System.out.println("换算后："+"width = "+ (width*25.4/72) +", height = "+ (height*25.4/72) );

            for (int i = 1; i <= pageTotalNum; i++) {
                int page = i;
                pdfReaderContentParser.processContent(i, new RenderListener() {
                    StringBuilder sb = new StringBuilder("");
                    String signKeyWord = keyword;
                    int maxLength = keyword.length();
                    @Override
                    public void renderText(TextRenderInfo textRenderInfo) {
                        String text = textRenderInfo.getText(); // 整页内容
//                        if (text != null && text.contains(signature.getKeyWord())) {
//                            // 文字在page中的横坐标、纵坐标
//                            Rectangle2D.Float textFloat = textRenderInfo.getBaseline().getBoundingRectange();
//                            float x = textFloat.x;
//                            float y = textFloat.y;
//                            signature.setX(x / width);
//                            signature.setY((height - y) / height);
//                            signature.setPageNum(page);
////                            System.out.println(String.format("第" + page + "盖章文字域绝对位置为x:%s,y:%s", x, y));
//                        }

                        // 只适用 单字块文档 以及 关键字整个为一个块的情况
                        // 设置 关键字文本为单独的块，不然会错位
                        boolean isKeywordChunk = textRenderInfo.getText().length() == maxLength;
                        if (isKeywordChunk) {
                            if(text != null && !text.trim().isEmpty()) {
                                // 文档按照 块 读取
                                sb.delete(0, sb.length());
                                sb.append(textRenderInfo.getText());

                            }
                        } else {
                            // 有些文档 单字一个块的情况
                            // 拼接字符串
                            if(text != null && !text.trim().isEmpty()) {
                                sb.append(textRenderInfo.getText());
                                // 去除首部字符串，使长度等于关键字长度
                                if (sb.length() > maxLength) {
                                    sb.delete(0, sb.length() - maxLength);
                                }
                            }
                        }
                        // 判断是否匹配上
                        if (signKeyWord.equals(sb.toString())) {
                            TempleteRecordSignature signatureDto = new TempleteRecordSignature();
                            // 计算中心点坐标
                            com.itextpdf.awt.geom.Rectangle2D.Float baseFloat = textRenderInfo.getBaseline() .getBoundingRectange();
                            com.itextpdf.awt.geom.Rectangle2D.Float ascentFloat = textRenderInfo.getAscentLine() .getBoundingRectange();

                            float centreX;
                            float centreY;
                            if (isKeywordChunk) {
                                centreX = baseFloat.x + ascentFloat.width / 2;
                                centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                            } else {
                                centreX = baseFloat.x + ascentFloat.width - (maxLength * ascentFloat.width / 2);
                                centreY = baseFloat.y + ((ascentFloat.y - baseFloat.y) / 2);
                            }

                            signatureDto.setX(centreX / width+"");
//                            if(centreY > height){
//                                signatureDto.setY((height - (centreY - height)) / height+"");
//                            }else{
                                signatureDto.setY((height - centreY) / height+"");
//                            }
                            signatureDto.setPage(page);
                            signatureDtos.add(signatureDto);

//                            result[0] = centreX/width;
//                            result[1] = (height - centreY)/height;
//                            System.out.println(String.format("第"+finalI+"页 "+signKeyWord+" 文字域绝对位置为x:%s,y:%s", centreX,centreY));


                            // 匹配完后 清除
                            sb.delete(0, sb.length());
                        }


                    }

                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void endTextBlock() {
                        // TODO Auto-generated method stub
                    }

                    @Override
                    public void beginTextBlock() {
                        // TODO Auto-generated method stub

                    }
                });
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return signatureDtos;
    }

    public static void main(String[] args) {
        List<TemplateFieldsDto> templateFieldsDtos = new ArrayList<>();
        TemplateFieldsDto templateFieldsDto = new TemplateFieldsDto();
        templateFieldsDto.setSort(5);
        TemplateFieldsDto templateFieldsDto1 = new TemplateFieldsDto();
        templateFieldsDto1.setSort(2);
        TemplateFieldsDto templateFieldsDto2 = new TemplateFieldsDto();
        templateFieldsDto2.setLabel("1");
        templateFieldsDto2.setSort(3);
        TemplateFieldsDto templateFieldsDto3 = new TemplateFieldsDto();
        templateFieldsDto3.setLabel("2");
//        templateFieldsDto3.setSort(3);
        templateFieldsDtos.add(templateFieldsDto);
        templateFieldsDtos.add(templateFieldsDto1);
        templateFieldsDtos.add(templateFieldsDto2);
        templateFieldsDtos.add(templateFieldsDto3);

    }

    public void updateTempleteStatus(Long id, Integer status, SysUser manager) {
        UpdateWrapper<Templete> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(Templete.COL_TEMPLETE_STATUS, status)
                .set(Templete.COL_UPDATE_BY, manager.getUserId())
                .set(Templete.COL_UPDATE_TIME, new Date())
                .eq(Templete.COL_ID, id);
        super.update(updateWrapper);
    }


    /**
     * app端模版展示, 先展示企业模版,在展示公共模版
     * @param manager
     * @param page
     * @param listMode
     * @param queryItems
     * @param orderField
     * @param order
     * @return
     */
    public IPage<Templete> queryAppContractTemplateList(SysUser manager, Page<Templete> page, boolean listMode, String queryItems, String orderField, QueryOrderEnum order) {
        QueryWrapper<Templete> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(Templete.COL_STATUS,"1");
        if (!manager.isHasRole(Constant.SUPER_ADMIN)) {//超级管理员
            queryWrapper.and(w -> w.eq(Templete.COL_COMPANY_ID, manager.getCompanyId()).or().eq(Templete.COL_COMPANY_ID, 0));
        }
        queryWrapper.orderByDesc(Templete.COL_COMPANY_ID).orderByAsc(Templete.COL_TEMPLETE_NAME);
        IPage<Templete> result = baseMapper.selectPage(page, queryWrapper);
        for (Templete record : result.getRecords()) {
            Long companyId = record.getCompanyId();
            if (companyId == 0) {
                record.setCompanyName("公共模板库");
            } else if(companyId > 0){
                Company company = companyService.getById(companyId);
                if(company != null){
                    record.setCompanyName(company.getName());
                }
            }
        }

        return result;
    }
}
